<?php


namespace App\Http\Controllers\Api;


use App\Models\ApiResult;
use App\Models\Content;
use App\Services\Base\CommonService;
use App\Services\Base\HelpService;
use Illuminate\Http\Request;

class CommonController extends ApiBaseController
{
    public function requestCode(Request $request, CommonService $service)
    {
        $data = $request->all();
        if ($vr = $this->verifyField($data, [
            'name' => 'bail|required|email|min:8|max:64',
        ])) return $vr;

        $data['lang'] = $this->getDefaultLang($request);
        $result = $service->requestCode($data);
        if ($result) {
            return $this->success($result);
        } else {
            return $this->failure();
        }
    }

    public function requestCodeKey(Request $request, CommonService $service)
    {
        $data = $request->all();
        $data['lang'] = $this->getDefaultLang($request);
        $result = $service->requestCodeKey($data);
        if ($result) {
            return $this->success($result);
        } else {
            return $this->failure();
        }
    }

    public function actionUpload(Request $request)
    {
        $uploadFailed = trans('cs.upload_failed');

        try {
            $file = $request->file('image');
            if ($file && $file->isValid()) {
                //本地保存
                $path = g_upload_path();
                $originalName = $file->getClientOriginalName(); // 文件原名
                $uploadName = time() . md5($originalName) . "." . $file->getClientOriginalExtension();
                $path = $file->storeAs($path, $uploadName, 'api');

                if ($path) {
                    return $this->responseJson(ApiResult::success(['path' => $path,
                        'display_path' => $request->getSchemeAndHttpHost() . "/uploads/" . $path],
                        trans('cs.upload_success')));
                } else {
                    return $this->responseJson(ApiResult::failure(500, $uploadFailed));
                }
            } else {
                return $this->responseJson(ApiResult::failure(500, $uploadFailed));
            }
        } catch (\Exception $e) {
            HelpService::log($e);
            return $this->responseJson(ApiResult::failure(500, $uploadFailed));
        }
    }

    public function downloadAndroidAuthenticator()
    {
        $fileName = "Google Authenticator_v5.10.apk";
        $filePath = public_path('uploads/files/' . $fileName);
        return response()->download($filePath);
    }

    public function config(Request $request)
    {
        $uid = $this->getUid($request);
        return $this->success([
            "cs_link" => config("base.cs_link", "https://www.baidu.com"),
            "login_available" => !empty($uid), // 如客户端拿到false，需要主动清空客户端token等登录信息
            "notification" => Content::notificationHome(),
        ]);
    }

}
